from flask import request, jsonify
from flask.views import MethodView
from app.models.category import Category
from webargs import fields
from webargs.flaskparser import parser
from ..auth import auth_required

parser_args = {
    'page': fields.Int(missing=0, error_messages={'invalid': '必须是数值类型'})
}


class CategoryAPI(MethodView):
    decorators = [auth_required]

    def get(self, id):
        if id is not None:
            data = Category.query.get_or_404(id).to_dict()
            return jsonify(success=True, data=data)

        else:
            args = parser.parse(parser_args, request)
            data = Category.to_collection_dict(Category.query, args['page'])
            return jsonify(success=True, data=data)

    def post(self):
        pass
